﻿#include "ssCamera.h"
#include "../../3dMath/ss3dMathFunction.h"
#include "../../node/ssNode.h"


namespace StarSeeker
{

ssCamera* ssCamera::s_currentCamera = 0;
ssCamera* ssCamera::s_mainCamera = 0;

ssCamera::ssCamera(void)
{
	m_type = SS_COMPONENT_CAMERA;
	m_cameraType = CAMERA_TYPE_NULL;
	m_matProj.Identity();
	m_matProjView.Identity();
	m_pmatView = 0;
	//SetView();
}

ssCamera::~ssCamera(void)
{
	if (ssCamera::s_currentCamera ==this)
	{
		ssCamera::s_currentCamera = 0;
	}
	if (ssCamera::s_mainCamera == this)
	{
		ssCamera::s_mainCamera = 0;
	}
}

const StarSeeker::ssFLOAT4x4X& ssCamera::GetProjMatrix()
{
	return m_matProj;
}

const StarSeeker::ssFLOAT4x4X& ssCamera::GetViewMatrix()
{
	if (m_pmatView)
	{
		return *m_pmatView;
	}
	else
	{
		return cg_identityMat4x4;
	}
}

const StarSeeker::ssFLOAT4x4X& ssCamera::GetProjViewMatrix()
{
	ComputeProjViewMatrix();
	return m_matProjView;
}

void ssCamera::SetProjMatrix(ssFLOAT4x4X &p)
{
	m_matProj = p;
}

bool ssCamera::IsType(CAMERA_TYPE type)
{
	return m_cameraType == type;
}

void ssCamera::ClearBuffer()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}

void ssCamera::ActiveCamera()
{
	ssCamera::s_currentCamera = this;
//#if defined(SS_USE_GLES2) || defined(SS_USE_ANDROID)
//	glColor3f(1, 1, 1);
//	glDrawBuffer(GL_BACK);
//#endif
	glEnable(GL_DEPTH_TEST);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
}

void ssCamera::InactiveCamera()
{
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_BLEND);
}

void ssCamera::SetMainCamera()
{
	ssCamera::s_mainCamera = this;
}

bool ssCamera::Render2Texture(GLenum attachmentPoint, GLuint textureId)
{
	if (!m_fbo.IsCreate())
	{
		if (m_fbo.Create())
		{
			m_fbo.BindTexture(attachmentPoint, textureId);
			return m_fbo.IsValid();
		}
	}
	return false;
}

void ssCamera::DelRender2Texture()
{
	if (m_fbo.IsCreate())
	{
		m_fbo.Nonuse();
		m_fbo.Delete();
	}
}

bool ssCamera::R2TBegin()
{
	if (m_fbo.IsCreate())
	{
		m_fbo.Use();
		return true;
	}
	return false;
}

void ssCamera::R2TEnd()
{
	if (m_fbo.IsCreate())
	{
		m_fbo.Nonuse();
	}
}

void ssCamera::OnAdd()
{
	m_pmatView = &m_pNode->Transform().ViewMatrix();
}

void ssCamera::ComputeProjViewMatrix()
{
	Math3D::FLOAT4x4XMultiply(&m_matProjView, m_pmatView, &m_matProj);
}

}
